package tw.com.guestbook.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import tw.com.guestbook.client.Post;
import tw.com.guestbook.client.PostService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class PostServiceImpl extends RemoteServiceServlet implements
		PostService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public boolean savePost(Post post) {
		boolean saved = false;
		try {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			pm.makePersistent(post);
			saved = true;
			pm.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return saved;
	}

	@Override
	public boolean updatePost(Post post) {
		boolean updated = false;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Post p = (Post) pm.getObjectById(Post.class, post.getId());
		try {
			p.setNickname(post.getNickname());
			p.setTitle(post.getTitle());
			p.setContent(post.getContent());
			p.setDate(new Date());
			updated = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
		return updated;
	}

	@Override
	public List<Post> getAllPosts() {
		List<Post> posts = new ArrayList<Post>();
		try {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery("SELECT FROM " + Post.class.getName());
			@SuppressWarnings("unchecked")
			List<Post> results = (List<Post>) query.execute();

			for (Post p : results) {
				posts.add(p);
			}
			pm.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return posts;
	}

	@Override
	public boolean deletePost(Post post) {
		boolean deleted = false;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Post p = (Post) pm.getObjectById(Post.class, post.getId());
			pm.deletePersistent(p);
			deleted = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
		return deleted;
	}
}
